# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.signals import post_save
from django import forms
from django.forms.forms import BoundField
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from timezones.fields import TimeZoneField
import datetime

from pygments.styles import get_all_styles

import registration.signals
from projects.models import Project, Screenshot
from pygameweb import markup

CONTACT_CHOICES = (
    ("none", "No contact"),
    ("form", "Contact form (without showing your email)"),
    ("users", "Show email address to authenticated users"),
    ("all", "Show email address to all visitors")
)
                                                
STYLES = [(name[:8], name) for name in sorted(get_all_styles())]
STYLES.insert(0, ("default", "default"))

PUBLIC_CHOICES = (
    (0, "No one"),
    (1, "Users"),
    (2, "Guests")
)

PUBLIC_DEFAULT = 1

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)
    display_name = models.CharField("Display Name", max_length=50,
                    unique=True, default="",
                    help_text=("This name will be used on the website to " +
                               "refer to you. It is not restricted like "+
                               "your username and you can change it whenever " +
                               "you want. (Defaults to your username)"))
    # website customization
    time_zone = TimeZoneField("Time Zone", choices=settings.TIMEZONE_CHOICES,
                    help_text="Your local time zone")                               
    website_theme = models.CharField(max_length=8, choices=settings.THEMES,
                    default = settings.DEFAULT_THEME,
                    )
    pygments_style = models.CharField(max_length=8, choices=STYLES,
                    default = settings.DEFAULT_STYLE,
                    help_text="Name of the pygments style to use for highlighted source code.")
    # public profile information
    website = models.URLField(blank=True,
                    help_text="Your personal website.")
    irc_nick = models.CharField("IRC Nick", blank=True, null=True, max_length=50, unique=True,
                    help_text="Your nick at freenode. You should only insert a registered nick." )
    languages = models.CharField(blank=True, max_length=150,
                    help_text="Languages you master (separate by comma)")
    markup = models.CharField(max_length=5, choices=markup.CHOICES,
                    default = markup.CHOICES[0][0],
                    help_text="What markup you want to use.")
    description = models.TextField(blank=True,
                    help_text=("Say something about yourself or whatever "+
                               "you want to. (optional)"))
    raw_description = models.TextField(blank=True, editable=False)
    contact = models.CharField(max_length=5, choices=CONTACT_CHOICES, 
                    default="form", help_text="Who should be able to contact you.")
    # privacy settings
    show_bookmarks = models.SmallIntegerField(choices=PUBLIC_CHOICES, 
                    default=PUBLIC_DEFAULT,
                    help_text="Show others your bookmarks")
    show_timezone = models.SmallIntegerField(choices=PUBLIC_CHOICES, 
                    default=PUBLIC_DEFAULT,
                    help_text="Show others your timezone")
    show_status = models.SmallIntegerField("Show status",
                    choices=PUBLIC_CHOICES, 
                    default=PUBLIC_DEFAULT, 
                    help_text="Show others when you are online")
    

    def admin_projects(self):
        return self.user.admins.order_by("name")
    
    def get_projects(self):
        a_projects = self.admin_projects()
        m_projects = self.member_projects()
        length = max(len(a_projects), len(m_projects))
        l = []
        for i in xrange(length):
            a_p = a_projects[i] if i < len(a_projects) else None
            m_p = m_projects[i] if i < len(m_projects) else None
            l.append((a_p, m_p))
        return l
        
    
    def member_projects(self):
        return self.user.members.order_by("name")
    
    def screenshots(self):
        return Screenshot.objects.filter(uploaded_by=self.user)
        
    @models.permalink
    def get_absolute_url(self):
        return ('profiles_profile_detail', (), { 'username': self.user.username })

    def save(self):
        """
        render markup to html before saving
        """
        if self.display_name == "":
            self.display_name = self.user.username
        self.render_markup()
        super(Profile, self).save() 
        
    def render_markup(self):
        self.raw_description = markup.render(self.description, self.markup)

    def __unicode__(self):
        return "%s (%s)" % (self.display_name, self.user.username)


class StructuredForm:
    group_struct = []
    def groups(self):
        group_list = []
        for name, fields in self.group_struct:
            group_list.append((name, [BoundField(self, 
                                           self.fields[fname],
                                           fname) for fname in fields]))
        return group_list


class MyProfileForm(forms.ModelForm, StructuredForm):
        group_struct = ((None,
                                ["display_name"]),
                           ("settings",
                                ["time_zone", "website_theme", 
                                 "pygments_style"]),
                           ("public profile", 
                                ["website", "irc_nick", "languages", "markup", 
                                 "description"]),
                           ("privacy settings", 
                                ["contact", "show_bookmarks", "show_timezone", 
                                 "show_status"]))
        
        class Meta:
            model = Profile
            exclude = ('user','raw_description')
            
        


def create_profile(sender, instance, created, **kw):
    if created:
        # make sure there is no profile connected to this user
        try:
            instance.get_profile()
        except ObjectDoesNotExist:
            i = 0
            while True:
                if not Profile.objects.filter(display_name=instance.username + str(i or "")):
                    break
		i += 1
            p = Profile(user=instance, display_name=instance.username + str(i or ""))
            p.save()

post_save.connect(create_profile, sender=User)



    
 
